import { Component, EventEmitter, Injector, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { CreateMenuItemInput,UpdateMenuItemInput, 
    NameValue,
    NavigationServiceProxy,
    IDropDownSelectionsDto,
    MenuItemDto } from '@shared/service-proxies/service-proxies';
import { map as _map } from 'lodash-es';
import { finalize } from 'rxjs/operators';


@Component({
    selector: 'addMenu',
    templateUrl: './add-menu.component.html',
})
export class AddMenuComponent extends AppComponentBase implements OnInit, OnChanges{

    editing = false;

    @Input() readonly :boolean = false;
    @Input() tenantId :number =  null;

    @Output() menuCreated: EventEmitter<MenuItemDto> = new EventEmitter<MenuItemDto>();
    @Output() menuUpdated: EventEmitter<MenuItemDto> = new EventEmitter<MenuItemDto>();

    saving = false;
    multiLocal = false;
    parentDisplayName : string = '';

    selects: IDropDownSelectionsDto = {
        deviceType: [],
        backendMenuType: [],
        backEndModule: [],
        itemGroups: [],
        local: false,
        displayType: [],
    };
    
    get menuItemDto(): MenuItemDto {
        return this._menuItemDto;
    }

    set menuItemDto(ou: MenuItemDto) {
        if (!ou) {
            this.resetData();
            return;
        }

        let item = new MenuItemDto();
        Object.assign(item,ou);
        this._menuItemDto = item;
        this._menuItemDto.backEndModuleId = !this._menuItemDto.backEndModuleId? '#':this._menuItemDto.backEndModuleId;
        this._menuItemDto.frontEndPageId= !this._menuItemDto.frontEndPageId ? '#':this._menuItemDto.frontEndPageId;
        this._menuItemDto.displayType= !this._menuItemDto.displayType ? 0:this._menuItemDto.displayType;
        this._menuItemDto.deviceType = !this._menuItemDto.deviceType ? 0:this._menuItemDto.deviceType;
        this._menuItemDto.backendMenuType = !this._menuItemDto.backendMenuType ? 0:this._menuItemDto.backendMenuType;
        this._menuItemDto.isActive= !this._menuItemDto.isActive ? false:this._menuItemDto.isActive;
        this._menuItemDto.isNavigation4FrontEnd = !this._menuItemDto.isNavigation4FrontEnd ? false : this._menuItemDto.isNavigation4FrontEnd;
        this.menuItemGroupArray = this.toIntArray(this._menuItemDto.menuItemGroups);
        
        if(!this.readonly){
            this.editing = true;
        }
    }

    menuItemGroupArray: string[] = [];

    private _menuItemDto: MenuItemDto;
    
    frontEndPages: { [key: string]: NameValue[] } = {};

    dataSynchronous: boolean = false;

    constructor(
        injector: Injector,
        private _navigationService: NavigationServiceProxy,
    ) {
        super(injector);
        this.resetData();
        this.dataSynchronous = this.setting.getBoolean("App.Synchronous.DataSynchronous");
    }

    private toIntArray(str) {
        var intArr = [];
        if (str) {
            var arr = str.split(',');
            for (var i = 0; i < arr.length; i++) {
                intArr.push(parseInt(arr[i]));
            }
        } else {
            intArr.push(0);
        }
        return intArr;
    }

    private resetData(){
        this._menuItemDto =  null;
    }

    ngOnInit(): void {
        this.getSelectsData();
    }
    ngOnChanges(changes: SimpleChanges): void {
        if (changes['tenantId']) {
            if (this.tenantId) {
                this.getSelectsData();
            }
        }
    }

    getRouteStr(){

    }
    
    save(): void {
        if (!this.menuItemDto.id) {
            this.addMenu();
        } else {
            this.updateMenu();
        }
    }
    
    private addMenu(): void {
        const input = new CreateMenuItemInput({
            displayName: this.menuItemDto.displayName,
            displayType: this.menuItemDto.displayType,
            deviceType: this.menuItemDto.deviceType,
            parentId: this.menuItemDto.parentId,
            isActive: this.menuItemDto.isActive,
            isNavigation4FrontEnd: this.menuItemDto.isNavigation4FrontEnd,
            isSpecial: this.menuItemDto.isSpecial,
            homeRecommendation: this.menuItemDto.homeRecommendation,
            channelRecommendation: this.menuItemDto.channelRecommendation,
            autoSynchronous: this.menuItemDto.autoSynchronous,
            autoSynchronousForContent: this.menuItemDto.autoSynchronousForContent,
            a: false,
            backEndModuleId: this.menuItemDto.backEndModuleId=="#"?null:this.menuItemDto.backEndModuleId,
            frontEndPageId: this.menuItemDto.frontEndPageId=="#"?null:this.menuItemDto.frontEndPageId,
            routeUrlStr: this.menuItemDto.routeUrlStr,
            menuItemGroups: this.menuItemGroupArray.join(','),
            localDisplayName: this.menuItemDto.localDisplayName,
            customUrl: this.menuItemDto.customUrl,
            customData: this.menuItemDto.customData,
            backendIcon: this.menuItemDto.backendIcon,
            backendMenuType: this.menuItemDto.backendMenuType
        });
        
        this.saving = true;
        this._navigationService
            .createMenuItem(input)
            .pipe(finalize(() => this.saving = false))
            .subscribe((result:MenuItemDto) => {
                this.notify.success(this.l('SuccessfullyAdded'));
                this.menuItemDto = result;
                this.menuCreated.emit(result);
            });
    }

    private updateMenu(): void {
        const input = new UpdateMenuItemInput({
            id: this.menuItemDto.id,
            displayName: this.menuItemDto.displayName,
            displayType: this.menuItemDto.displayType,
            deviceType: this.menuItemDto.deviceType,
            isNavigation4FrontEnd: this.menuItemDto.isNavigation4FrontEnd,
            isSpecial: this.menuItemDto.isSpecial,
            isActive: this.menuItemDto.isActive,
            homeRecommendation: this.menuItemDto.homeRecommendation,
            channelRecommendation: this.menuItemDto.channelRecommendation,
            autoSynchronous: this.menuItemDto.autoSynchronous,
            autoSynchronousForContent: this.menuItemDto.autoSynchronousForContent,
            backEndModuleId: this.menuItemDto.backEndModuleId=="#"?null:this.menuItemDto.backEndModuleId,
            frontEndPageId: this.menuItemDto.frontEndPageId=="#"?null:this.menuItemDto.frontEndPageId,
            menuItemGroups: this.menuItemGroupArray.join(','),
            backendMenuType: this.menuItemDto.backendMenuType,
            lastModificationTime: this.menuItemDto.lastModificationTime,
            routeUrlStr: this.menuItemDto.routeUrlStr,
            customUrl: this.menuItemDto.customUrl,
            customData: this.menuItemDto.customData,
            backendIcon: this.menuItemDto.backendIcon,
            localDisplayName:this.menuItemDto.localDisplayName
        });
        this.saving = true;
        this._navigationService
            .updateMenuItem(input)
            .pipe(finalize(() => this.saving = false))
            .subscribe((result:MenuItemDto) => {
                this.notify.success(this.l('SavedSuccessfully'));
                this.menuItemDto = result;
                this.menuUpdated.emit(result);
            });
    }

    private getSelectsData():void{
        let tenantId = this.tenantId;
        if(!tenantId){
            tenantId = this.appSession.tenantId;
        }

        this._navigationService.getDropDownSelectionsData(tenantId).subscribe(result => {
            this.selects = result;
            this.multiLocal = result.local;

            result.backEndModule.forEach(item =>{
                this.frontEndPages[item.value] = item.child;
            });
        });
    }

    close() {
        this.resetData();
    }
}
